package com.ktkj.init.controller;

import com.ktkj.init.response.Response;
import com.ktkj.init.response.ResponseCallBack;
import com.ktkj.init.response.ResponseCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


@Api(tags = "上传文件夹")
@RestController
@RequestMapping(path = "/uploadDir")
@CrossOrigin
@Slf4j
public class UploadDirController {
    //String html = "D:\\idea_workspace_kt\\project\\HTML\\uploadDir.html";

    @Value("${upload.file.path}")
    private String uploadFilePath;

    @ApiOperation(value = "上传文件夹至本地")
    @PostMapping(path = "/test1", headers = "content-type=multipart/form-data")
    public Response test1(@RequestParam("file") final MultipartFile[] file) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                try {
                    for (MultipartFile mf : file) {
                        //获取文件名的全路径
                        String originalFilename = mf.getOriginalFilename();
                        log.info("originalFilename={}",originalFilename);
                        //先创建文件夹
                        String dirPath = originalFilename.substring(0, originalFilename.lastIndexOf("/"));
                        File fileDir = new File(uploadFilePath + dirPath);
                        fileDir.mkdirs();
                        //然后保存文件到对应的文件夹
                        File fileData = new File(uploadFilePath + originalFilename);
                        mf.transferTo(fileData);
                        log.info("上传文件夹.成功|");
                    }
                } catch (Exception e) {
                    log.error("上传文件夹.error|", e);
                }
                criteria.addSingleResult(true);
            }
        }.sendRequest();
    }

}
